package com.webull.information.center.dao;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import com.webull.information.client.model.NewsLabelRel;

/**
 * 新闻-标签 关系dao.
 *
 * @author longyang
 * @date 2016年6月27日 下午8:03:18
 * @version 1.0
 * @since JDK 1.8
 */

/*
 * 暂不启用的代码，使用前需更新逻辑和测试
 */

@Deprecated
@Repository
public class InfoNewsLabelRelDao {
	private static final RowMapper<NewsLabelRel> newsLableRelRM = BeanPropertyRowMapper.newInstance(NewsLabelRel.class);
	protected final Logger logger = LogManager.getLogger(getClass());
	private @Autowired JdbcTemplate jdbcTemplate;
	private @Autowired NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	public int add(NewsLabelRel newsLabelRel) {
		logger.trace("sql={}, label={}", Sql.ADD, ToStringBuilder.reflectionToString(newsLabelRel));
		KeyHolder keyHolder = new GeneratedKeyHolder();
		namedParameterJdbcTemplate.update(Sql.ADD, JdbcHelper.getSqlParameterSource(newsLabelRel), keyHolder);
		int id = keyHolder.getKey().intValue();
		newsLabelRel.setId(id);
		return id;
	}

	public Integer delByNewsId(Long newsId) {
		logger.trace("sql={}, newsId={}", Sql.DEL_BY_NEWS_ID, newsId);
		return jdbcTemplate.update(Sql.DEL_BY_NEWS_ID, newsId);
	}

	public Integer del(Integer... relIds) {
		if (relIds != null && relIds.length > 0) {
			logger.trace("sql={}, ids={}", Sql.DEL, relIds);
			Map<String, Object> paraMap = new HashMap<>();
			paraMap.put("ids", Arrays.asList(relIds));
			return namedParameterJdbcTemplate.update(Sql.DEL, paraMap);
		}
		return null;
	}

	public List<NewsLabelRel> searchByNewsId(Long newsId) {
		logger.trace("sql={}, newsId={}", Sql.SEARCH_BY_NEWS_ID, newsId);
		return jdbcTemplate.query(Sql.SEARCH_BY_NEWS_ID, new Object[] { newsId }, newsLableRelRM);
	}

	private class Sql {
		public static final String ADD = "insert into wli_news_label_rel (news_id, label_id, create_time) values (:newsId, :labelId, now())";
		public static final String DEL = "update wli_news_label_rel set del=1 where id in (:ids)";
		public static final String DEL_BY_NEWS_ID = "update wli_news_label_rel set del=1 where news_id=?";
		public static final String SEARCH_BY_NEWS_ID = "select * from wli_news_label_rel where del=0 and news_id=?";
	}
}
